/*
 * Copyright (c) 2012 Aleksander Zotov, Benedikt Markt, Aliaksei Babkovich
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 *  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 *  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 *  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
 *  THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package database;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import utils.Debug;

/**
 * This class represents a website that has a database of objects in space as
 * TLE data and contains the login data needed to retrieve these datasets
 * 
 * @author Benedikt Markt
 * @see SourceDB
 * @see SpaceTrackLogin
 */
public class AGILogin extends SourceDB {

	public AGILogin() {
		name = "AGI";
		url = "https://www.agi.com";
	}

	public AGILogin(String username, String password) {
		this.username = username;
		this.password = password;

		name = "AGI";
		url = "https://www.agi.com";
	}

	@Override
	public void download(String name) throws IOException {

		// Connection String
		URL url = new URL("ftp://ftp.stk.com/dist/satdb/stkAllTLE40.ZIP");
		URLConnection con = url.openConnection();

		BufferedInputStream in = new BufferedInputStream(con.getInputStream());
		File agiZipFile = new File(".\\agiTLE.zip");
		FileOutputStream out = new FileOutputStream(agiZipFile);

		int i = 0;
		byte[] bytesIn = new byte[1024];
		while ((i = in.read(bytesIn)) >= 0) {
			out.write(bytesIn, 0, i);
		}
		out.close();
		in.close();
		try {
			extractArchive(agiZipFile, new File(".\\tmp\\" + name));
		} catch (Exception e) {
			Debug.log(Debug.ERROR, "Unable to unzip file");
		}
		
		Path allTLE = Paths.get(".\\tmp\\" + name + "\\stkAllTLE.tce");
		Path catalogCato = Paths.get(".\\users\\" + name + "\\catalog.cato");
		if(catalogCato.toFile().exists()) {
			catalogCato.toFile().delete();
		}
		Files.copy(allTLE,  catalogCato);
		
		deleteDirectory(new File(".\\tmp\\" + name));
		

	}

	@Override
	public boolean isAvailable() {
		return isCorrectLogin();
	}

	@Override
	public boolean isCorrectLogin() {
		return true;
	}

	public void extractArchive(File archive, File destDir) throws Exception {
		if (!destDir.exists()) {
			destDir.mkdir();
		}

		ZipFile zipFile = new ZipFile(archive);
		Enumeration entries = zipFile.entries();

		byte[] buffer = new byte[16384];
		int len;
		while (entries.hasMoreElements()) {
			ZipEntry entry = (ZipEntry) entries.nextElement();

			String entryFileName = entry.getName();

			File dir = buildDirectoryHierarchyFor(entryFileName, destDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}

			if (!entry.isDirectory()) {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(new File(destDir, entryFileName)));

				BufferedInputStream bis = new BufferedInputStream(
						zipFile.getInputStream(entry));

				while ((len = bis.read(buffer)) > 0) {
					bos.write(buffer, 0, len);
				}

				bos.flush();
				bos.close();
				bis.close();
			}
		}
		zipFile.close();
	}

	private File buildDirectoryHierarchyFor(String entryName, File destDir) {
		int lastIndex = entryName.lastIndexOf('/');
		String internalPathToEntry = entryName.substring(0, lastIndex + 1);
		return new File(destDir, internalPathToEntry);
	}
	
	private void deleteDirectory(File f) {
		if (f.isDirectory()) {
			for (File c : f.listFiles()) {
				deleteDirectory(c);
			}
		}
		f.delete();
	}

}
